<?php
namespace gnomephp\mvc;

/**
 *
 * All controllers should implement this class.
 * @author peec
 *
 */


abstract class Controller{

	/**
	 *
	 * Holds the View class.
	 * @var gnomephp\mvc\View
	 */
	public $view;

	/**
	 *
	 * Holds the model loader class.
	 * @var gnomephp\mvc\Model
	 */
	protected $model;


	/**
	 * Holds the input class.
	 * @var gnomephp\input\Input
	 */
	protected $input;


	/**
	 * Holds the input class.
	 * @var gnomephp\helper\lang\Lang
	 */
	protected $lang;

	/**
	 * Holds the input class.
	 * @var gnomephp\Session
	 */
	public $session;

	/**
	 * Notifier class, holds notification classes such as mail methods.
	 * @var gnomephp\mvc\Notifier
	 */
	protected $notifier;

	
	/**
	 * Captcha class, used for validation of captcha images that are created with the Captcha gnomephp\form\Captcha class.
	 * To generate captcha, see \gnomephp\form\Form
	 * @var gnomephp\captcha\Captcha
	 */
	protected $captcha;
	
	/**
	 * State class, holds the state class, you can save the current state.
	 * Some handlers will redirect to the previous state if the state was saved.
	 * @var gnomephp\mvc\State
	 */
	protected $state;

	public function __construct(){
		$this->input = new \gnomephp\input\Input;
		$this->session = new \gnomephp\Session();

		$this->lang = new \gnomephp\helper\lang\Lang($this->session);
		
		
		$this->notifier = new Notifier;

		$this->view = new View($this->input, $this->lang, $this->session);
		$this->model = new Model;

		$this->state = new State($this->session);

		
		$this->captcha = new \gnomephp\captcha\Captcha($this->session, $this->input);
	}

	/**
	 * Redirects user to a url, use in conjunction with $this->url->link(...) or use normal http://google.com as argument.
	 * @param string $url The url to locate to.
	 */
	public function redirect($url){

		// Keep message flash.
		$msgs = \gnomephp\message\Message::getMessages();
		if (count($msgs) > 0){
			$this->session->set('gnomephp.messages', $msgs);
			$this->session->save();
		}

		header('Location: '.$url);
		die();
	}



	/**
	 * This function tries first to redirect to previously saved state.
	 * If it does not exist, normal redirect will be done to the url.
	 * 
	 * After redirection to state, the previous state will be deleted.
	 * @param string $url The url to redirect to if no state was found.
	 */
	public function redirectStateFirst($url){
		// If we have a previous state we want to redirect to the same state
		if ($state = $this->state->getSavedState()){
			// Delete the previous state.
			$this->state->deleteState();
			// Execute the state.
			echo $state->execute();
				
			// If we have no previous state, lets redirect user to the manage page.
		}else{
			$this->redirect($url);
		}
	}




}